package com.cn.crmsystem.controller.businessController;

import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Api(value = "下载文档",tags ="下载文档接口API" )
public class UploadDowLoadController {

   /* @RequestMapping("/uploadFile")
    public  String  uploadFile(@RequestParam("headImg") CommonsMultipartFile headImg) throws IOException {//request  part
        //CommonsMultipartFile headImg  临时文件
        String fileName=headImg.getOriginalFilename();//获取文件名
        //获取后缀
        String newFileName= UUID.randomUUID().toString().replace("-","")
                +fileName.substring(fileName.lastIndexOf("."));//工具类执行
        System.out.println("文件的新名字"+newFileName);
        //实例化一个文件对象
        File newFile=new File("D:\\Pictures",newFileName);
        //CommonsMultipartFile  复制
        headImg.transferTo(newFile);//  把临时文件中 内容复制给newFile
        return  "index.jsp";
    }*/

    @RequestMapping("/downFile")
    public ResponseEntity<byte[]> downFile(String filePath, HttpServletRequest  request) throws IOException {
        System.out.println("相对路径"+filePath);
        //获取文件的绝对路劲
        //获取项目部署的地址  getRealPath
         String realPath=  request.getServletContext().getRealPath(filePath);
        System.out.println(realPath);
        //新的名字
        String  fileName=filePath.substring(filePath.lastIndexOf("/")+1);//System.currentTimeMillis()+filePath.substring(filePath.lastIndexOf("."));
         //中文转码
        fileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
    /*    InputStream  in=new FileInputStream(realPath);
        //byte[] */
        //springMVC 写法
        //设置  hread     content-disposition attachment;fileName=
        //设置请求头信息
        HttpHeaders   httpHeaders=new HttpHeaders();
        //设置下载的附件
        httpHeaders.setContentDispositionFormData("attachment",fileName);
        //设置MIME类型
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                                        //文件的工具包FileUtils
        return  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new  File(realPath)),httpHeaders, HttpStatus.CREATED);

    }


}
